<!-- 新建编辑表情包管理和IP形象新建编辑 共用一个页面 -->
<template>
  <div class="create-mengli">
    <div :class="{'mobile-create': showMobilePage}" class="mengli-form">
      <Title :title="pageTitle" font-size="16px" style="margin-bottom: 16px" />
      <div v-show="!isEdit && !isIpImage" class="flex-center create-type-box" >
        <el-radio-group v-model="radioCreateType" class="radio-group" @change="createTypeChange">
          <div class="fb-radio" style="margin-right: 32px">
            <el-radio :label="0">新建IP</el-radio>
          </div>
          <div class="fb-radio">
            <el-radio :label="1">已有IP</el-radio>
          </div>
        </el-radio-group>
        <el-select v-if="createType === 1" v-model="selectEmojiIp" popper-class="global-select-down" name="ipId" @change="emojiIpSelected">
          <el-option label="请选择" value="" />
          <el-option
            v-for="(item, index) in emojiIps"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="ip-info-box">
        <ip-info-edit v-if="createType === 0 && !isEdit" ref="ipInfoEdit" :ip-info="ipInfo" :is-ip-image="isIpImage" :default-params="defaultParams" :relevant-list="relevantList" @update:formValid="updateIpInfoValid" @update:ipInfo="updateIpInfo" @getRelevantName="getRelevantName"/>
        <ip-info v-if="(createType === 1 || isEdit ) && mengliIpDetail" :ip-info="ipInfo" :info="mengliIpDetail" @update:ipInfo="updateIpInfo" />
      </div>
      <div v-if="!isIpImage" :class="{'work-info-box': !showMobilePage}">
        <div :class="{ 'cursor-frobid': !isAllowSwitchUpload }" :style="{ 'marginBottom': isUpload ? '32px' : '0px'}" class="upload-btn" @click="uploadWorkSwitch">
          {{ isUpload ? '取消新建' : '新建作品' }}
          <img v-if="isUpload" :src="iconNoUpload" alt="crm系统">
          <img v-else :src="iconUpload" alt="crm系统">
        </div>
        <div class="upload-work-box">
          <div v-show="isUpload">
            <work-info-edit ref="workInfoEdit" :work-info="workInfo" @update:formValid="updateWorkInfoValid" @update:workInfo="updateWorkInfo" />
            <upload-button
              :get-list="uploadComplate"
              :hide-confirm="true"
              import-api="/admin/mengli/upload"
              btn-text="上传报表"
              @complateSetData="imageUpdateSuccess"
            />
            <div class="img-list">
              <imageList
                :list="imageList"
                @deleteImg="deleteImg"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <fixed-pagination>
      <div class="center">
        <el-button v-if="createType === 1 && mengliIpDetail || createType === 0" :loading="toSaveLoad" type="primary" size="small" @click="toSave">保存</el-button>
        <el-button type="info" size="small" class="cancel-btn-style" @click="toBack">取消</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>
<script>
import {
  createMengli,
  editMengli,
  getOptionsIp,
  getMengliIpDetail,
  getRelatedList,
  createMengliIpImage } from '@/api/mengli';
import uploadButton from '@/components/Mengli/uploadMenli';
import imageList from '@/components/Mengli/imageShowList';
import ElMessage from '@/utils/message';
import Title from '@/components/Title';
import IpInfoEdit from './module/ip-info-edit';
import workInfoEdit from './module/work-info-edit';
import IpInfo from './module/ip-info';
import iconUpload from '@/assets/icon-upload-white.png';
import iconNoUpload from '@/assets/icon-no-upload.png';
import { mapState } from 'vuex';

export default {
  components: { uploadButton, imageList, Title, IpInfoEdit, workInfoEdit, IpInfo },
  data() {
    return {
      /* 请求参数-start- */
      ipId: '',
      workId: '',
      radioCreateType: 0,
      defaultParams: {}, // 默认选项
      ipInfo: {
        ipName: '',
        range: '',
        cover: '',
        ipSeriesId: 0,
        relevantIds: [],
        supplierId: '',
        accreditCost: '',
        ecomSaleCost: ''
      },
      workInfo: {
        workName: '',
        stickerId: '',
        downloadNum: '',
        publishTime: '',
        sendNum: '',
        effect: '',
        rewardPrice: '',
        workCover: '',
        type: '',
        rewardNum: ''
      },
      imageList: [], // 作品图片
      /* -end- */
      /* 暂存作品参数-start- */
      cacheWorkInfo: {
        '0': {
          workName: '',
          stickerId: '',
          downloadNum: '',
          publishTime: '',
          sendNum: '',
          effect: '',
          rewardPrice: '',
          type: '',
          rewardNum: '',
          imageList: []
        },
        '1': {
          workName: '',
          stickerId: '',
          downloadNum: '',
          publishTime: '',
          sendNum: '',
          effect: '',
          rewardPrice: '',
          type: '',
          rewardNum: '',
          imageList: []
        }
      },
      /* -end- */
      /* 暂存ipInfo作品参数 -start */
      cacheIpInfo: {
        '0': {
          ipName: '',
          range: '',
          cover: '',
          relevantIds: [],
          supplierId: '',
          accreditCost: '',
          ecomSaleCost: ''
        },
        '1': {
          ipName: '',
          range: '',
          cover: '',
          relevantIds: [],
          supplierId: '',
          accreditCost: '',
          ecomSaleCost: ''
        }
      },
      /* -end- */
      iconUpload,
      iconNoUpload,
      isEdit: false,
      createType: 0, // 新建ip类型 0:新建ip 1:已有ip
      antiShakeTime: 0, // 防抖时间
      ipInfoFormValid: false, // ip 信息模块的表单验证结果
      workInfoFormValid: false, // 作品模块的表单验证结果
      emojiIps: [],
      selectEmojiIp: '',
      mengliIpDetail: '', // 表情包详情
      isUpload: false, // 是否上传作品
      ipUpload: false,
      newUpload: false,
      toSaveLoad: false,
      relevantLoading: false,
      relevantName: '',
      relevantList: {},
      isIpImage: false, // 是否为新增或者编辑IP形象
      pageTitle: ''
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAllowSave() {
      if (this.createType === 0 && !this.isEdit) {
        return this.ipInfoFormValid && (!this.isUpload || this.workInfoFormValid);
      } else {
        return !this.isUpload || this.workInfoFormValid;
      }
    },
    isAllowSwitchUpload() {
      if (this.isEdit) return false;
      if (this.createType === 1 && !this.mengliIpDetail) return false;
      return true;
    },
    isShowSaveBtn() {
      return this.createType === 0 || this.createType === 1 && this.isUpload;
    }
  },
  created() {
    console.log(this.showMobilePage);
    const route = this.$route;
    this.isIpImage = route.name === 'mengliIpImageCreate';
    if (route.path.indexOf('edit') >= 0) {
      this.isEdit = true;
      this.isUpload = true;
      const { ipId, workId } = this.$route.query;
      this.ipId = ipId;
      this.workId = workId;
      this.getMengliIpDetail(ipId);
    } else {
      const createType = this.$route.query.createType || 0;
      if (createType && Number(createType) === 1) {
        this.createType = Number(createType);
        this.radioCreateType = Number(createType);
        this.createTypeChange(1);
      }
      this.isEdit = false;
    }
    this.pageTitle = this.isIpImage ? 'IP形象信息' : (this.isEdit ? '编辑表情包表情' : '新建表情包表情');
    this.getRelatedList();
  },
  mounted() {
    const that = this;
    const SELECTWRAP_DOM = document.querySelector('.user-select .el-select-dropdown__wrap');
    if (SELECTWRAP_DOM) {
      SELECTWRAP_DOM.addEventListener('scroll', function() {
        const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight;
        if (CONDITION) {
          that.relevantLoadMore();
        }
      });
    }
    window.remoteRequest('.remoteRequest1', this.getRelevantName);
  },
  methods: {
    uploadComplate() {

    },
    uploadWorkSwitch() {
      if (this.isEdit) return;
      if (this.createType === 0) {
        this.isUpload = !this.isUpload;
      } else {
        if (this.mengliIpDetail) {
          this.isUpload = !this.isUpload;
        }
      }
    },
    // 滑动加载关联表情包列表
    relevantLoadMore() {
      const relevantList = this.relevantList;
      const currentPage = relevantList.page;
      const isMax = relevantList.items.length >= relevantList.total;
      if (!isMax && !this.relevantLoading) {
        this.getRelatedList(currentPage + 1);
      }
    },
    getRelevantName(data) {
      this.relevantName = data;
      this.getRelatedList();
    },
    getRelatedList(toPage = 1) {
      this.relevantLoading = true;
      const params = {
        relevantName: this.relevantName,
        page: toPage,
        perPage: 20
      };
      getRelatedList(params).then(({ data }) => {
        this.relevantLoading = false;
        this.relevantList = data;
      }).catch(err => {
        this.relevantLoading = false;
        console.log(err);
      });
    },
    toSubmit() {
      if (this.isEdit) {
        this.editMengli();
      } else {
        this.createMengli();
      }
    },
    createMengli(params) {
      const request = this.isIpImage ? createMengliIpImage(params) : createMengli(params);
      request.then(res => {
        if (res.code === 200) {
          ElMessage.success('创建成功');
          this.$router.push({
            name: 'Mengli'
          });
          this.toBack();
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        console.log(err);
      });
    },
    editMengli(params) {
      editMengli(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('编辑成功');
          this.$router.push({
            name: 'Mengli'
          });
          this.toBack();
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        console.log(err);
      });
    },
    // 删除单个表情
    deleteImg({ item, index }) {
      const imgList = this.imageList;
      // const index = imgList.findIndex(res => (res.id === item.id || res.url === item.url));
      imgList.splice(index, 1);
    },
    updateIpInfo(data) {
      this.ipInfo = data;
    },
    updateWorkInfo(data) {
      this.workInfo = data;
    },
    // 图片上传成功后更新
    imageUpdateSuccess({ data }) {
      this.imageList = [...this.imageList, ...data];
    },
    createTypeChange(type) {
      if (type) {
        this.cacheWorkInfo['0'] = this.workInfo;
        this.cacheWorkInfo['0']['imageList'] = this.imageList;
        this.cacheIpInfo['0'] = this.ipInfo;
        this.newUpload = this.isUpload;
        this.isUpload = this.ipUpload;
        this.workInfo = this.cacheWorkInfo[type];
        this.ipInfo = this.cacheIpInfo[type];
        this.imageList = this.cacheWorkInfo[type].imageList;
        if (this.emojiIps.length === 0) this.getEmojiIpList();
      } else {
        this.cacheWorkInfo['1'] = this.workInfo;
        this.cacheWorkInfo['1']['imageList'] = this.imageList;
        this.cacheIpInfo['1'] = this.ipInfo;
        this.workInfo = this.cacheWorkInfo[type];
        this.ipInfo = this.cacheIpInfo[type];
        this.imageList = this.cacheWorkInfo[type].imageList;
        this.ipUpload = this.isUpload;
        this.isUpload = this.newUpload;
      }
      this.createType = type;
    },
    emojiIpSelected(id) {
      this.getMengliIpDetail(id);
    },
    // 获取ip详情
    getMengliIpDetail(id) {
      const params = {
        id
      };
      getMengliIpDetail(params).then(res => {
        if (res.code === 200) {
          this.mengliIpDetail = res.data;
          this.ipId = id;
          this.initWorkInfo(res.data.workList);
          this.initIpInfo(res.data);
        }
      });
    },
    initWorkInfo(works) {
      if (works.length) {
        let i = 0;
        let data;
        while (i < works.length) {
          if (works[i].id === Number(this.workId)) {
            data = works[i];
            break;
          }
          i++;
        }
        if (!data) return;
        this.imageList = [...data.imageList];
        const workInfo = {
          workName: data.name,
          stickerId: data.stickerId,
          downloadNum: data.downloadNum,
          publishTime: data.publishTime,
          sendNum: data.sendNum,
          effect: data.effect ? data.effect : '',
          rewardPrice: data.rewardPrice,
          type: data.type ? data.type : '',
          rewardNum: data.rewardNum,
          workCover: data.cover
        };
        this.workInfo = workInfo;
      }
    },
    initIpInfo(data) {
      this.ipInfo.ipName = data.name;
      this.ipInfo.range = data.range;
      this.ipInfo.cover = data.cover;
      this.ipInfo.relevantIds = data.relevantIds;
    },
    // 获取已有表情包ip列表
    getEmojiIpList() {
      getOptionsIp().then(res => {
        if (res.code === 200) {
          this.emojiIps = res.data;
        }
      });
    },
    updateIpInfoValid(value) {
      this.ipInfoFormValid = value;
    },
    updateWorkInfoValid(value) {
      this.workInfoFormValid = value;
    },
    toSave() {
      var timestamp = new Date().getTime();
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      if (!this.isAllowSave) {
        // if (this.$refs['ipInfoEdit']) this.$refs['ipInfoEdit'].triggerFormValidate();
        // if (this.$refs['workInfoEdit']) this.$refs['workInfoEdit'].triggerFormValidate();
        this.$message({ type: 'warning', message: '请检查信息是否填写完整' });
        return;
      }
      let params;
      if (this.isEdit) {
        if (!this.workInfo.workCover) {
          this.$message({ type: 'warning', message: '请检查信息是否填写完整' });
          return;
        }
        params = { ...this.workInfo, ...this.ipInfo };
        params['imageList'] = this.imageList;
        params['ipId'] = this.ipId;
        params['id'] = this.workId;
        this.editMengli(params);
      } else {
        if (this.createType === 1) {
          if (this.isUpload && !this.workInfo.workCover) {
            this.$message({ type: 'warning', message: '请检查信息是否填写完整' });
            return;
          }
          params = { ...this.workInfo, ...this.ipInfo };
          params['ipId'] = this.ipId;
        } else {
          if ((this.isUpload && (!this.workInfo.workCover || !this.ipInfo.cover)) || (!this.isUpload && !this.ipInfo.cover)) {
            this.$message({ type: 'warning', message: '请检查信息是否填写完整' });
            return;
          }
          params = { ...this.workInfo, ...this.ipInfo, ipId: 0 };
        }
        params['imageList'] = this.imageList;
        this.createMengli(params);
      }
    },
    toBack() {
      if (this.isEdit) {
        this.$router.push({
          name: this.isIpImage ? 'mengliIpImage' : 'mengliDetail',
          params: { id: this.ipId },
          query: { workId: this.workId }
        });
      } else {
        this.$router.push({
          name: this.isIpImage ? 'mengliIpImage' : 'mengliPlanet'
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.create-mengli {
  .mengli-form {
    margin: 16px;
    min-height: calc(100vh - 70px);
    background-color: #fff;
    padding: 24px 24px 54px 24px;
    .create-type-box {
      height: 32px;
      margin-bottom: 16px;
      .radio-group {
        display: flex;
        margin-right: 8px;
      }
    }
    .ip-info-box {
      & ::v-deep {
        .el-select {
          .el-select__tags {
            .el-tag.el-tag--info {
              color: #888;
              border-color: #eee;
              background-color: #eee;
            }
          }
        }
      }
    }
    .work-info-box {
      margin-top: 30px;
    }
  }
  .crm-add-btn {
    margin-left: 32px;
    margin-bottom: 32px;
  }
  .img-list {
    margin-top: 20px;
  }
  .upload-btn {
    cursor: pointer;
    display: flex;
    justify-content: center;
    width: 120px;
    height: 32px;
    line-height: 32px;
    border-radius: 4px;
    font-size: 500;
    background-color: #406EFF;
    color: #fff;
    img {
      margin-left: 4px;
      width: 16px;
      height: 16px;
    }
  }
  .cursor-frobid {
    cursor: not-allowed;
  }
}
.mobile-create {
  padding: 12px 12px 54px !important;
  ::v-deep {
    .el-upload, .upload-btn, .user-select-component {
      width: 100% !important;
    }
    .ip-info-wrap {
      flex-direction: column;
      .left {
        margin-bottom: 8px;
      }
    }
  }
}
</style>
<style lang="scss">
.create-mengli {
  .el-input {
    width: 240px;
  }
  .el-input__inner {
    height: 32px;
    line-height: 32px;
    width: 240px;
  }
  .el-form-item{
    margin-bottom: 24px !important;
  }
  .el-input__icon {
    line-height: 32px;
  }
  .el-select {
    .el-input {
      .el-select__caret {
        color: #333333;
      }
    }
  }
}
</style>
